package cn.scut.srp.service.impl;

import cn.scut.srp.mapper.OrderInfoMapper;
import cn.scut.srp.mapper.StudentMapper;
import cn.scut.srp.model.BaseResponse;
import cn.scut.srp.model.ResponseCode;
import cn.scut.srp.model.entity.OrderInfo;
import cn.scut.srp.model.entity.Student;
import cn.scut.srp.service.PublicService;
import cn.scut.srp.utils.JWTUtils;
import cn.scut.srp.utils.ResponseUtil;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class PublicServiceImpl implements PublicService {

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private JWTUtils jwt;

    @Override
    public List<LocalDate> getWeek(Integer week) {
        ZoneId shanghaiZone = ZoneId.of("Asia/Shanghai");
        ZonedDateTime currentDateTime = ZonedDateTime.now(shanghaiZone);

        DayOfWeek startOfWeek = DayOfWeek.MONDAY;
        List<LocalDate> daysOfWeek = new ArrayList<>();

        LocalDate firstDayOfWeek = currentDateTime.toLocalDate();
        while (firstDayOfWeek.getDayOfWeek() != startOfWeek) {
            firstDayOfWeek = firstDayOfWeek.minusDays(1);
        }

        for (int i = 0; i < 7; i++) {
            daysOfWeek.add(firstDayOfWeek.plusDays(i + (7L * week)));
        }

        return daysOfWeek;
    }

    @Override
    public BaseResponse<ResponseCode> login(String username, String password) {
        Student student = studentMapper.getStudentByName(username);
        if(student == null){
            log.info("user {} not exist in database", username);
            return ResponseUtil.UserNotExist("用户不存在");
        }

        if(!student.getPassword().equals(password)){
            log.info("user {} has sent wrong password", username);
            return ResponseUtil.wrongPassword("密码错误");
        }
        String token = jwt.generateToken(student.getStudentAccount(),student.getStudentName(),student.getPassword());//成功了，返回token
        return ResponseUtil.OK(token);
    }

    @Override
    public BaseResponse<ResponseCode> getReserveByWeek(List<LocalDate> weekToSeek) {
        List<OrderInfo> dates = orderInfoMapper.findOrderInfoByDates(weekToSeek);
        if(dates == null || dates.size() == 0){
            return ResponseUtil.noSchedule("没有预约");
        }

        Object json = JSON.toJSON(dates);
        return ResponseUtil.OK(json);
    }
}
